package cn.yunhe.vote.dao.impl;

import cn.yunhe.vote.BaseDB;
import cn.yunhe.vote.dao.IVoteDao;
import cn.yunhe.vote.entity.Vote;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class VoteDao extends BaseDB implements IVoteDao {
    Connection conn = null;
    PreparedStatement psmt = null;
    ResultSet rs = null;

    @Override
    public boolean addVote(int id) {
        boolean flag = false;
        try {
            conn = getConn();
            String sql = "update t_vote set times=times+1 where id=?";
            psmt = conn.prepareStatement(sql);
            psmt.setInt(1, id);
            flag = psmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, psmt, rs);
        }
        return flag;
    }

    @Override
    public List<Vote> allVote() {
        List<Vote> list = new ArrayList<>();
        try {
            conn = getConn();
            String sql = "select * from t_vote";
            psmt = conn.prepareStatement(sql);
            rs = psmt.executeQuery();
            while (rs.next()) {
                Vote vote = new Vote(rs.getInt("id"), rs.getString("name"), rs.getInt("times"));
                list.add(vote);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, psmt, rs);
        }
        return list;
    }
}
